import React from 'react';
import {inject, observer} from 'mobx-react';
import {observable, action} from 'mobx';
import {routerShape} from 'react-router';
import isEmpty from 'lodash/isEmpty'
import {WeaTableNew} from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import {WeaForm, WeaSwitch} from 'comsMobx';
import {
  WeaTop,
  WeaTab,
  WeaLeftTree,
  WeaLeftRightLayout,
  WeaSearchGroup,
  WeaRightMenu,
  WeaPopoverHrm,
  WeaFormItem,
  WeaNewScroll
} from 'ecCom'
import RoomPlanDialog from '../public/roomPlan/index';

import {WeaErrorPage, WeaTools} from 'ecCom';
import {Button, Form} from 'antd';

let _this = null;
import MeetingDialog from '../public/dialog/index';
import {WeaLocaleProvider} from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

@inject('meetingSearch')
@inject('meetingDialog')
@observer
class Search extends React.Component {
  static contextTypes = {
    router: routerShape
  }

  constructor(props) {
    super(props);
    _this = this;
    this.state = {
      RoomPlanContainer: false,
      dialogType: 'preview',
      meetingId: '',
      visible: false,
    }

  }

  componentDidMount() {//一些初始化请求
    const {meetingSearch} = this.props;
    //初始化高级搜索区域
    meetingSearch.initDatas();
    meetingSearch.adSearchForm.updateFields(
      {
        names: {
          value: ''
        }
      },
      true
    );
    //初始化列表
    meetingSearch.doLoading();
  }

  componentWillReceiveProps(nextProps) {
    if(this.props.location.key !== nextProps.location.key) {
      const {meetingSearch} = this.props;
      //初始化列表
      meetingSearch.doLoading(meetingSearch.adSearchForm.getFormParams());
    }
  }

  componentWillUnmount() {
    //组件卸载时一般清理一些状态
    const {adSearchForm} = this.props.meetingSearch;
    adSearchForm.reset && adSearchForm.reset();
    const { meetingSearch } = this.props;
    meetingSearch.showSearchAd = false;
  }

  render() {
    const title = `${getLabel(16424,'查询会议')}`;
    let {RoomPlanContainer, visible, dialogType, meetingId} = this.state;
    const {meetingSearch} = this.props;
    const {loading, showSearchAd, dataKey, topTab} = meetingSearch;
    let {dialogStatus} = this.props.meetingDialog;
    let collectParams={
      favname: title,
      favouritetype: 5,
      objid: 0,
      importantlevel: 1,
    };
    return (
      <div className="metting-search">
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@hisr47`} datas={this.getRightMenu()} /* onClick={this.onRightMenuClick.bind(this)}*/ collectParams={collectParams}>
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@wsw4yw`}
            title={title}
            loading={loading}
            icon={<i className='icon-coms-meeting'/>}
            iconBgcolor='#f14a2d'
            buttons={this.getBtn()}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            onDropMenuClick={this.onRightMenuClick}
            dropMenuProps={{collectParams: collectParams}}
          >
            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@2penhk`}
              buttonsAd={this.getTabButtonsAd()}
              searchsBaseValue={meetingSearch.adSearchForm.getFormParams().names}
              // buttons={this.getBtn()}
              searchType={['base', 'advanced']}
              setShowSearchAd={bool => {
                meetingSearch.setShowSearchAd(bool)
              }}
              hideSearchAd={() => meetingSearch.setShowSearchAd(false)}
              searchsAd={<Form ecId={`${this && this.props && this.props.ecId || ''}_Form@4n3vfq`} horizontal>{this.getSearchs()}</Form>}
              showSearchAd={showSearchAd}
              selectedKey={meetingSearch.adSearchForm.getFormParams().timeSag ? meetingSearch.adSearchForm.getFormParams().timeSag : 0}
              onSearch={v => {
                meetingSearch.doLoading(meetingSearch.adSearchForm.getFormParams())
              }}
              onSearchChange={v => {
                meetingSearch.adSearchForm.updateFields(
                  {
                    names: {
                      value: v
                    },
                    timeSag__meetingStartdatefrom__meetingStartdateto: {
                      value: meetingSearch.adSearchForm.getFormParams().timeSag
                    }
                  },
                  true
                );
              }}
              keyParam="viewcondition"  //主键
              countParam="groupid" //数量
              onChange={this.changeData}
              datas={topTab}
            />
            {
              loading ? '' : meetingSearch.tableStore[dataKey] ?
                <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@fksbe1`}
                  hasOrder={true}
                  needScroll={true}
                  getColumns={this.getColumns}
                  sessionkey={dataKey}
                  comsWeaTableStore={meetingSearch.tableStore[dataKey]}
                /> : ''
            }
          </WeaTop>
          
        </WeaRightMenu>

        <MeetingDialog ecId={`${this && this.props && this.props.ecId || ''}_MeetingDialog@gzj2bz`}
          setRoomPlan={this.setRoomPlan}
          setDialog={this.setDialog}
          setType={this.setType}
          setMeetingId={this.setMeetingId}
          setAll={this.setAll}
          type={dialogType}//新建为'create',查看为'preview',编辑edit,会议决议---待定
          visible={visible}//显隐受控
          /* doClose={()=>{this.close()}}//关闭回调, 保存等按钮会自动调用该回调，可以在这里写一些页面的刷新操作 */
          /* onlyClose={() => { onlyClose() }}//关闭回调,关闭/取消等按钮会自动调用该回调，只做关闭操作 */
          doRefesh={this.doRefesh}//自定义刷新页面，不会关掉弹出框
          meetingId={meetingId} //会议id，查看会议时用到
          isInterval={false}//新建会议类型，true是周期会议， false是普通会议
          meetingDate={''}//新建日期
        />
        {RoomPlanContainer && <RoomPlanDialog ecId={`${this && this.props && this.props.ecId || ''}_RoomPlanDialog@nyunsv`}
          setRoomPlan={this.setRoomPlan}
          setDialog={this.setDialog}
          setType={this.setType}
          setMeetingId={this.setMeetingId}
          canCreate={false}
          height={600}
          visible={RoomPlanContainer}/>}
      </div>
    )
  }

  doRefesh = () => {
    const {meetingSearch} = this.props;
    this.props.meetingSearch.doLoading(meetingSearch.adSearchForm.getFormParams());
  }
  setAll = (meetingId, bool, type) => {
    this.setState({
      meetingId: meetingId,
      visible: bool,
      dialogType: type
    })
  }
  setMeetingId = (meetingId) => {
    this.setState({meetingId: meetingId})
  }
  setRoomPlan = (bool) => {
    this.setState({RoomPlanContainer: bool})
  }
  setDialog = (bool) => {
    this.setState({visible: bool})
  }
  setType = (type) => {
    this.setState({dialogType: type})
  }

  //右键菜单事件绑定
  onRightMenuClick = (key)=>{

    const {meetingSearch} = this.props;
    const { tableStore,dataKey } = meetingSearch;
    if (key == '0') {
      meetingSearch.doLoading(meetingSearch.adSearchForm.getFormParams());
      meetingSearch.setShowSearchAd(false);
    } else if (key == '1') {
      meetingSearch.adSearchForm.reset();
      meetingSearch.doLoading();
      meetingSearch.setShowSearchAd(false);
    }else if(key=='BTN_COLUMN'){
      tableStore[dataKey].setColSetVisible(true);
      tableStore[dataKey].tableColSet(true);
    } else if(key=='BTN_SEARCH'){
      meetingSearch.doLoading(meetingSearch.adSearchForm.getFormParams());
      // meetingSearch.setShowSearchAd(false);
    }

  }

  getColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map(column => {
      let newColumn = column;
      newColumn.render = (text, record, index) => { //前端元素转义
        let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
        return (
          newColumn.dataIndex == 'name' ?
            <a onClick={() => {
              this.setState({meetingId: record.id, visible: true})
              this.setType('preview')
            }} dangerouslySetInnerHTML={{ __html: valueSpan }} />
            :
            <div dangerouslySetInnerHTML={{ __html: valueSpan }} />
        )
      }
      return newColumn;
    });
    return newColumns;
  }
  //右键菜单
  getRightMenu() {
    let btns = [];
    const {meetingSearch} = this.props;
    const {tableStore,dataKey} = meetingSearch;
    btns.push({
      key: 'BTN_EXPORT',
      icon: <i className='icon-coms-download'/>,
      content : `${getLabel(81272,"导出全部")}`,
      onClick : () => meetingSearch.exportExcel(dataKey)
    });
    btns.push({
      key: 'BTN_SEARCH',
      icon: <i className='icon-coms-search'/>,
      content: getLabel(197, "搜索"),
      onClick : () => this.onRightMenuClick('BTN_SEARCH')
      
    });
    btns.push({
      key: 'BTN_COLUMN',
      icon: <i className='icon-coms-Custom'/>,
      content : `${getLabel(32535,'显示列定制')}`,
      onClick : () => this.onRightMenuClick('BTN_COLUMN')
    });
    return btns
  }

  onEnterSearch = ()=>{
    const {meetingSearch} = this.props;
    meetingSearch.doLoading(meetingSearch.adSearchForm.getFormParams());
    meetingSearch.setShowSearchAd(false)
  }

  //高级搜索group定义
  getSearchs() {
    // return [
    //     (<WeaSearchGroup needTigger={true} title={this.getTitle()} showGroup={this.isShowFields()} items={this.getFields()}/>),
    //     (<WeaSearchGroup needTigger={true} title={this.getTitle(1)} showGroup={this.isShowFields(1)} items={this.getFields(1)}/>)
    // ]
    const {meetingSearch} = this.props;
    const conditioninfo = meetingSearch.conditioninfo;
    const {adSearchForm} = meetingSearch;
    const {isFormInit} = adSearchForm;
    let group = [];
   // console.log(this.props)
    isFormInit && conditioninfo.map((c, index) => {
      let items = [];
      c.items.map(fields => {
        items.push({
          com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@sonrz6@${fields.domkey[0]}`}
            label={`${fields.label}`}
            labelCol={{span: `${fields.labelcol}`}}
            wrapperCol={{span: `${fields.fieldcol}`}}>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@1udadr@${fields.domkey[0]}`} fieldConfig={fields} form={adSearchForm} onChange={null/*todo*/} onEnterSearch={this.onEnterSearch}/>
          </WeaFormItem>),
          colSpan: 1
        })
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@3ab0p1@${index}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
    });
    return group;
  }

  getTitle(index = 0) {
    const {meetingSearch} = this.props;
    const {conditioninfo} = meetingSearch;
    return !isEmpty(conditioninfo) && conditioninfo[index].title
  }

  isShowFields(index = 0) {
    const {meetingSearch} = this.props;
    const {conditioninfo} = meetingSearch;
    if (conditioninfo.length == 0) {
      return true;
    }
    return !isEmpty(conditioninfo) && conditioninfo[index].defaultshow
  }

  // 0 常用条件，1 其他条件
  getFields(index = 0) {
    const {meetingSearch} = this.props;
    const {conditioninfo} = meetingSearch;
    const fieldsData = !isEmpty(conditioninfo) && conditioninfo[index].items;
    let items = [];
    // forEach(fieldsData, (field) => {
    //     items.push({
    //         com:(<FormItem
    //             label={`${field.label}`}
    //             labelCol={{span: `${field.labelcol}`}}
    //             wrapperCol={{span: `${field.fieldcol}`}}>
    //             {WeaTools.switchComponent(this.props, field.key, field.domkey, field)}
    //         </FormItem>),
    //         colSpan:1
    //     })
    // })
    return items;
  }

  //高级搜索底部按钮定义
  getTabButtonsAd() {
    const {meetingSearch} = this.props;
    return [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@q8wjbg@doSearch`} type="primary" onClick={() => {
        meetingSearch.doLoading(meetingSearch.adSearchForm.getFormParams());
        meetingSearch.setShowSearchAd(false)
      }}>{getLabel(197, "搜索")}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@d5pe7s@doReset`} type="ghost" onClick={() => {
        meetingSearch.adSearchForm.reset()
      }}>{getLabel(2022, "重置")}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@jr6kn0@doCancel`} type="ghost" onClick={() => {
        meetingSearch.setShowSearchAd(false)
      }}>{getLabel(201, "取消")}</Button>)
    ]
  }

  getButtons() {
    let btns = [];
    return btns
  }

  getBtn() {
    const {meetingSearch} = this.props;
    const {tableStore,dataKey} = meetingSearch;
    
    let btns = [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@4qz4i9@exportAll`} type="primary" disabled={false} onClick={() => {meetingSearch.exportExcel(dataKey)}}>{getLabel(81272,"导出全部")}</Button>),
    ];
    return btns;
  }

  changeData = (theKey)=>{
    const {meetingSearch} = this.props;
    meetingSearch.adSearchForm.updateFields({
      timeSag__meetingStartdatefrom__meetingStartdateto: {
        value: [theKey]
      }
    }, true);
    meetingSearch.setShowSearchAd(false);
    meetingSearch.doLoading({
      timeSag: meetingSearch.adSearchForm.getFormParams().timeSag
    });
  }

}

//组件检错机制
class MyErrorHandler extends React.Component {
  render() {
    const hasErrorMsg = this.props.error && this.props.error !== "";
    return (
      <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@ihfe3z`} msg={hasErrorMsg ? this.props.error : getLabel(383324, "对不起，该页面异常，请联系管理员")}/>
    );
  }
}

Search = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(Search);

export default Search
